#-*-coding:utf-8-*-
'''
file : search.py
handles expanding tricks like * in a current dir
'''



import os
import sys ; sys.path.append('../../')
import re

from shelltools.io.common import get_path_separator
from shelltools.io.dir import list_dir



def get_last_file(tdir,pattern=None):
    '''
    Retrieve the last modified file name of the directory tdir
    following the pattern if specified
    @param tdir : the directory to process
    @returns the last modified file name in tdir
    '''
    #Sanitize param used by function 
    if not tdir.endswith(get_path_separator()) :
        tdir += get_path_separator()
    #Get the list of the targetdir
    rawlist = list_dir(tdir)
    #if there is no files, exit
    if not rawlist : return False
    #if a search pattern is defined
    if pattern :
        files = [tdir+f for f in rawlist if (os.path.isfile(tdir+f) and re.search(pattern,f) != None)]
    else :
        files = [tdir+f for f in rawlist if os.path.isfile(tdir+f)]
    
    if len(files) != 0 :
        return max(files,key=os.path.getmtime) # return the last file following key getmtime from os.path
    else :
        return False # no files where found matching the given pattern or directory

if __name__=='__main__':
    get_last_file('.',"\.*\\.txt")
